﻿using System;
using System.Collections.Concurrent;
using System.Linq;
using HttpApiGateway.Interface;
using RpcHelper;

namespace HttpApiGateway.Collect
{
    internal class ApiModularCollect
    {
        private static readonly ConcurrentDictionary<string, IApiModular> _ModularList = new ConcurrentDictionary<string, IApiModular>();

        public static IApiModular Find(Type type)
        {
            string[] keys = _ModularList.Keys.ToArray();
            foreach (string i in keys)
            {
                IApiModular modular = _ModularList[i];
                if (modular.CheckIsContain(type))
                {
                    return modular;
                }
            }
            return null;
        }
        public static IApiModular Sync(Type type)
        {
            string[] keys = _ModularList.Keys.ToArray();
            foreach (string i in keys)
            {
                IApiModular modular = _ModularList[i];
                if (modular.CheckIsContain(type))
                {
                    return modular;
                }
            }
            IApiModular m = new DefModular(type);
            _ModularList.TryAdd(m.ServiceName, m);
            return m;
        }
        public static bool RegModular(IApiModular modular, out string error)
        {
            if (_ModularList.ContainsKey(modular.ServiceName))
            {
                error = "http.api.modular.repeat";
                return false;
            }
            else if (!_ModularList.TryAdd(modular.ServiceName, modular))
            {
                error = "http.api.modular.reg.error";
                return false;
            }
            else
            {
                error = null;
                return true;
            }
        }
    }
}
